using SqlSugar;
using StudyCompanion.Core.Enum;
using StudyCompanion.Core.Repository;
using StudyCompanion.Core.Services;
using StudyCompanion.Entity.Order;
using StudyCompanion.Entity.User;
using StudyCompanion.IServices;

namespace StudyCompanion.Services;

/// <summary>
/// 事务处理服务
/// </summary>
public class EventHandleAppService : BaseService, IEventHandleAppService
{
    private readonly BaseRepository<Users> _userRepository;
    private readonly BaseRepository<Order> _orderRepository;
    private readonly BaseRepository<UseWalletLogEntity> _walletLogRepository;
    private readonly IWalletLogService _walletLogService;

    public EventHandleAppService(BaseRepository<Users> userRepository,
        BaseRepository<Order> orderRepository,
        BaseRepository<UseWalletLogEntity> walletLogRepository,
        IWalletLogService walletLogService)
    {
        _userRepository = userRepository;
        _orderRepository = orderRepository;
        _walletLogRepository = walletLogRepository;
        _walletLogService = walletLogService;
    }

    /// <summary>
    /// 返佣
    /// </summary>
    /// <param name="orderId"></param>
    /// <param name="serialNumber"></param>
    /// <exception cref="NotImplementedException"></exception>
    public async Task RebateAndUpgrade(long orderId, string? serialNumber)
    {
        var orderInfo = _orderRepository.Where(x => x.Id == orderId && x.Status == (int)OrderStatusEnum.Unpaid).First();
        if (orderInfo == null) return;
        var userInfo = _userRepository.Where(x => x.Id == orderInfo.UserId).First();
        var superInfo = _userRepository.Where(x => x.Id == userInfo.SuperiorUser).First();
        if (superInfo == null) return;
        orderInfo.Status = (int)OrderStatusEnum.Paid;
        orderInfo.TradeState = (int)TradeStateEnum.SUCCESS;
        orderInfo.PayNumber = serialNumber;
        orderInfo.PayTime = DateTime.Now;
        
        try
        {
            _walletLogRepository.BeginTran();
            await _walletLogRepository.Change<Order>().UpdateAsync(orderInfo);
            _walletLogService.WriteWalletLog(superInfo.Id, WalletActionEnum.Rebate, WalletTypeEnum.Add, orderInfo.Rebate,
                orderInfo.Id, $"用户:{userInfo.Id}({userInfo.NickName}),购买月卡返利", null);
            _walletLogRepository.CommitTran();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        finally
        {
            _walletLogRepository.RollbackTran();
        }
    }
    
}